import axios from 'axios'
import notification from 'ant-design-vue/es/notification'
import Engines from '@/utils/engine.js'
import { getToken, removeToken } from '@/utils/util'
import { RSA_NO_PADDING } from 'constants'

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

const service = axios.create({
  withCredentials: true,
  timeout: 20000,
  headers: {
    'Content-Type': 'application/json'
  }
})
service.interceptors.request.use(
  config => {
    if (getToken('pssid')) {
      config.headers['Authorization'] = getToken('pssid');
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (navigator) {
      if (!navigator.onLine) {
        notification.error({
          message: '请检查网络是否连接',
          description: ''
        })
        return Promise.reject(res.msg || 'error')
      }
    }
    // 有些返回结果没有code 比如，图形验证码
    if (res.code) {
      if (res.code != 200) {
        if (res.code != 1206) {
          notification.error({
            message: res.msg,
            description: ''
          })
        }

        // if (res.code == 100007 || res.code == 200002) {
        //   removeToken('pssid');
        //   window.location.reload()
        // }
        if (res.code == '4001') {
          notification.error({
            message: '登录过期了',
            description: ''
          })
          setTimeout(() => {
            removeToken('pssid');
            window.location.reload()
          }, 2000)
          return false
        }
        return Promise.reject(res || 'error')
      } else {
        return res
      }
    } else {
      return res
    }
  },
  error => {
    if (JSON.stringify(error).indexOf('4001') > -1) {
      notification.error({
        message: '登录过期了',
        description: ''
      })
      setTimeout(() => {
        removeToken('pssid');
        window.location.reload()
      }, 2000)
      return false
    }
    if (error.code === 'ECONNABORTED' && error.msg.indexOf('timeout') !== -1) {
      notification.error({
        message: '网络请求超时',
        description: ''
      })
    } else {
      notification.error({
        message: '网络错误',
        description: ''
      })
    }
    return Promise.reject(error)
  }
)

export default service
